import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IDEA
 * Author: LuoHengYi
 * Date: 2022/6/17
 * Time: 11:02
 */
public class Receiver {
    public static void main(String[] args) {


        //创建链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        //作用域，不同的业务可以分配不同的作用域 /order ，/message
        connectionFactory.setVirtualHost("/");

        //网络异常自动连接恢复
        connectionFactory.setAutomaticRecoveryEnabled(true);
        // 每3秒尝试重试连接一次
        connectionFactory.setNetworkRecoveryInterval(3000);


        Connection connection = null;
        try {
            //创建链接
            connection = connectionFactory.newConnection();

            //每个Channel代表一个会话任务,类似sqlsession
            Channel channel = connection.createChannel();

            //创建一个消费者 // 消费者订阅消息 监听如上声明的队列
            DefaultConsumer defaultConsumer = new DefaultConsumer(channel){

                @Override
                public void handleRecoverOk(String consumerTag) {
                    super.handleRecoverOk(consumerTag);
                    System.out.println("----------->"+consumerTag);
                }

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    System.out.println(consumerTag);
                    System.out.println(envelope.toString());
                    System.out.println(properties.toString());
                    System.out.println( "消息内容:" + new String(body));
                }
            };

            //队列名称
            String queueName="test001";

            //设置队列名称、消息自动ack(标记该消费成功)、消费者
            channel.basicConsume(queueName,false,defaultConsumer);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }


    }
}
